package com.app.common

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.view.WindowManager
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner

var progressDialog: Dialog? = null
var messageView: TextView? = null
var loadingHandler: Handler? = null
var lastContext: Context? = null
var loadingTime = 0L

@SuppressLint("InflateParams")
fun showProgressDialog(
    context: Context,
    block: () -> Unit,
    message: Int = R.string.text_loading,
    loadingDuration: Long = 10000L
) {
    if (context !is LifecycleOwner) {
        Log.e("123->", "Context must be LifecycleOwner")
        return
    }

    (context as LifecycleOwner).lifecycle.addObserver(object : LifecycleEventObserver {
        override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
            when (event) {
                Lifecycle.Event.ON_DESTROY -> {
                    if (loadingTime != 0L) {
                        dismissProgressDialog()
                    }
                    progressDialog = null
                    messageView = null
                }
                else -> Unit
            }
        }
    })

    if (loadingHandler != null) {
        loadingHandler?.removeCallbacksAndMessages(null)
    } else {
        loadingHandler = Handler(Looper.getMainLooper())
    }
    if (progressDialog != null && context == lastContext) {
        if (message == -1) {
            messageView?.text = ""
        } else {
            messageView?.text = context.resources.getString(message)
        }
        progressDialog?.window?.setBackgroundDrawable(
            ColorDrawable(
                context.applicationContext.resources.getColor(android.R.color.transparent)
            )
        )
        val lp = progressDialog?.window?.attributes
        lp?.alpha = 0.7f
        progressDialog?.window?.attributes = lp
        progressDialog?.window?.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
        loadingTime = System.currentTimeMillis()
        progressDialog?.show()
        loadingHandler?.postDelayed({
            if (loadingTime != 0L) {
                dismissProgressDialog()
                Toast.makeText(context, R.string.text_time_out, Toast.LENGTH_SHORT).show()
                block()
            }
        }, loadingDuration)
        return
    }
    lastContext = context
    val view = LayoutInflater.from(context)
        .inflate(R.layout.dialog_simple_progress, null)
    messageView = view.findViewById<TextView>(R.id.dialogMessage)
    if (message == -1) {
        messageView?.text = ""
    } else {
        messageView?.text = context.resources.getString(message)
    }
    progressDialog?.dismiss()
    progressDialog = Dialog(context)
    progressDialog?.setContentView(view)
//    progressDialog = AlertDialog.Builder(context).setView(view).create()
    progressDialog?.setCanceledOnTouchOutside(false)
    progressDialog?.setCancelable(false)
    progressDialog?.window?.setBackgroundDrawable(
        ColorDrawable(
            context.applicationContext.resources.getColor(
                android.R.color.transparent
            )
        )
    )
    val lp = progressDialog?.window?.attributes
    lp?.alpha = 0.7f
    progressDialog?.window?.attributes = lp
    progressDialog?.window?.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)

    progressDialog?.setOnDismissListener {
        loadingTime = 0
        loadingHandler?.removeCallbacksAndMessages(null)
        progressDialog?.window?.clearFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND or WindowManager.LayoutParams.FLAG_DIM_BEHIND)
    }
    loadingTime = System.currentTimeMillis()
    progressDialog?.show()
    loadingHandler?.postDelayed({
        if (loadingTime != 0L) {
            dismissProgressDialog()
            Toast.makeText(context, R.string.text_time_out, Toast.LENGTH_SHORT).show()
            block()
        }
    }, loadingDuration)
}

fun dismissProgressDialog() {
    if (progressDialog != null) {
        progressDialog?.dismiss()
    }
}

@SuppressLint("InflateParams")
fun showProgressDialog(
    context: Context,
    block: () -> Unit,
    message: String = context.getString(R.string.text_loading),
    loadingDuration: Long = 10000L
) {
    if (context !is LifecycleOwner) {
        Log.e("123->", "Context must be LifecycleOwner")
        return
    }

    (context as LifecycleOwner).lifecycle.addObserver(object : LifecycleEventObserver {
        override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
            when (event) {
                Lifecycle.Event.ON_DESTROY -> {
                    if (loadingTime != 0L) {
                        dismissProgressDialog()
                    }
                    progressDialog = null
                    messageView = null
                }
                else -> Unit
            }
        }
    })

    if (loadingHandler != null) {
        loadingHandler?.removeCallbacksAndMessages(null)
    } else {
        loadingHandler = Handler(Looper.getMainLooper())
    }
    if (progressDialog != null && context == lastContext) {
        messageView?.text = message
        progressDialog?.window?.setBackgroundDrawable(
            ColorDrawable(
                context.applicationContext.resources.getColor(android.R.color.transparent)
            )
        )
        val lp = progressDialog?.window?.attributes
        lp?.alpha = 0.7f
        progressDialog?.window?.attributes = lp
        progressDialog?.window?.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
        loadingTime = System.currentTimeMillis()
        progressDialog?.show()
        loadingHandler?.postDelayed({
            if (loadingTime != 0L) {
                dismissProgressDialog()
                Toast.makeText(context, R.string.text_time_out, Toast.LENGTH_SHORT).show()
                block()
            }
        }, loadingDuration)
        return
    }
    lastContext = context
    val view = LayoutInflater.from(context)
        .inflate(R.layout.dialog_simple_progress, null)
    messageView = view.findViewById<TextView>(R.id.dialogMessage)
    messageView?.text = message
    progressDialog = Dialog(context)
    progressDialog?.setContentView(view)
//    progressDialog = AlertDialog.Builder(context).setView(view).create()
    progressDialog?.setCanceledOnTouchOutside(false)
    progressDialog?.setCancelable(false)
    progressDialog?.window?.setBackgroundDrawable(
        ColorDrawable(
            context.applicationContext.resources.getColor(
                android.R.color.transparent
            )
        )
    )
    val lp = progressDialog?.window?.attributes
    lp?.alpha = 0.7f
    progressDialog?.window?.attributes = lp
    progressDialog?.window?.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)

    progressDialog?.setOnDismissListener {
        loadingTime = 0
        loadingHandler?.removeCallbacksAndMessages(null)
        progressDialog?.window?.clearFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND or WindowManager.LayoutParams.FLAG_DIM_BEHIND)
    }
    loadingTime = System.currentTimeMillis()
    progressDialog?.show()
    loadingHandler?.postDelayed({
        if (loadingTime != 0L) {
            dismissProgressDialog()
            Toast.makeText(context, R.string.text_time_out, Toast.LENGTH_SHORT).show()
            block()
        }
    }, loadingDuration)
}